package com.ml.mall.service.ipay.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ml.mall.bean.req.ipay.Ipay88CallBackDto;
import com.ml.mall.bean.req.order.OrderEditReq;
import com.ml.mall.consts.CommonConsts;
import com.ml.mall.consts.OrderStateConsts;
import com.ml.mall.entity.company.SysCompany;
import com.ml.mall.entity.payinfo.SysPayinfo;
import com.ml.mall.entity.payinfo.SysPaymentRecord;
import com.ml.mall.mapper.company.SysCompanyMapper;
import com.ml.mall.service.asyn.OrderMailServiceImplAsyn;
import com.ml.mall.service.company.SysCompanyService;
import com.ml.mall.service.ipay.Ipay88Service;
import com.ml.mall.service.mail.MailService;
import com.ml.mall.service.order.SysOrderService;
import com.ml.mall.service.payinfo.SysPayinfoService;
import com.ml.mall.service.payinfo.SysPaymentRecordService;
import com.ml.mall.service.supplier.SysOrderSupplierService;
import com.ml.mall.utils.HttpUtil;
import com.ml.mall.utils.SHA256;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

/**
 * @description description
 * @author yx
 * @date 2021/9/22
 * @version 1.0
*/
@Service
@Slf4j
public class Ipay88ServiceImpl implements Ipay88Service {

    @Autowired
    private SysPayinfoService sysPayinfoService;

    @Autowired
    private SysOrderService sysOrderService;

    @Autowired
    private SysCompanyMapper sysCompanyMapper;

    @Autowired
    private OrderMailServiceImplAsyn orderMailServiceImplAsyn;

    @Autowired
    private SysPaymentRecordService sysPaymentRecordService;

    @Autowired
    private SysOrderSupplierService sysOrderSupplierService;

    @Override
    @Transactional
    public void receiveCallBack(Ipay88CallBackDto dto) throws NoSuchAlgorithmException {
        //检测Ip
        log.info("==reciveIpay88CallBack==getIp===[{}]", HttpUtil.getIp());
        //检验加密
        BigDecimal amountDecimal  = new BigDecimal(dto.getAmount()).multiply(new BigDecimal(100));
        Long amountLong = amountDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).longValue();
        String paramStr =   CommonConsts.MERCHANTKEY + CommonConsts.MERCHANTCODE + dto.getPaymentId() + dto.getRefNo() + amountLong + "MYR" + dto.getStatus() ;
        String mysign = SHA256.calculateSha256(paramStr);
        log.info("paramStr====={}",paramStr);
        log.info("mysign====={}",mysign);
        log.info("getSignature====={}",dto.getSignature());
        if(mysign.equals(dto.getSignature())){
            log.info("==sign==id===correct===[{}]",dto.getRefNo());
            //检测订单是否存在；
            LambdaQueryWrapper<SysPayinfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysPayinfo::getPayId,dto.getRefNo());
            SysPayinfo sysPayinfo =  sysPayinfoService.getOne(queryWrapper);
            if(sysPayinfo == null){
                log.info("ipay88CallBack======notExistedPayInfo==id=={}", dto.getRefNo());
                return;
            }
            //检测是否已支付
            if(CommonConsts.ORDER_STATE_PAID.equals(sysPayinfo.getState())){
                log.info("ipay88CallBack======ischangede");
                return ;
            }
            //检测金额
            if(sysPayinfo.getMoney().compareTo(new BigDecimal(dto.getAmount())) > 0){
                log.info("ipay88CallBack=======Money==less==");
                return;
            }
            //更新支付信息
            boolean isUpdated = sysPayinfoService.updateByCallBackDto(dto);

            //添加支付记录
            sysPaymentRecordService.saveByCallBackDto(dto);

            Long oid = Long.valueOf(dto.getRefNo());
            Long companyId = oid;
            //如果是成功更新订单状态为已支付
            if(isUpdated && Integer.parseInt(dto.getStatus()) == CommonConsts.ORDER_STATE_PAID){
                log.info("reciveIpay88CallBack====update==orderIsSuccess===={}",dto.getRefNo());
                //如果是商户费用支付更新支付；
                if(CommonConsts.PAY_ORDER_TYPE_ORDER.equals(sysPayinfo.getType())){
                    log.info("reciveIpay88CallBack===is========order======");
                    companyId = sysOrderService.orderCompanyQuery(oid).getCompanyId();
                    OrderEditReq orderEditReq = new OrderEditReq();
                    orderEditReq.setOid(oid);
                    orderEditReq.setState(CommonConsts.ORDER_STATE_PAID.toString());
                    //更新买家订单
                    sysOrderService.sysOrderEdit(orderEditReq);
                    //更新卖家订单状态
                    sysOrderSupplierService.sysOrderSupplierEditByOid(orderEditReq);
                }else{
                    log.info("reciveIpay88CallBack===is========dealer======");
                    //更新商户为已支付
                    sysCompanyMapper.updateCompanyIsPaid(companyId);
                }
                //邮件通知商户
                orderMailServiceImplAsyn.createPurchaseOrderPaymentMadeMailAsyn(companyId);
            }
        }else{
            log.info("ERR====SIGN==mysign={}",mysign);
        }
    }
}
